package org.example.dyscript.dynamicscript;

import lombok.SneakyThrows;
import ognl.*;

import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.util.Map;

public class OGNLRule implements Rule {

  static MemberAccess memberAccess = new AbstractMemberAccess() {
    @Override
    public boolean isAccessible(Map context, Object target, Member member, String propertyName) {
      int modifiers = member.getModifiers();
      return Modifier.isPublic(modifiers);
    }
  };

  private OgnlContext rootContext;

  Object executeExpression;
  Object evaluateExpression;

  String executeScript = "#ali_score > 100 && #wx_score < 450 && ! #pd_living_province.contains(\"乌克兰\") "
      + "&& #pd_census_province.contains(\"吉尔吉斯斯坦\")";

  String evaluateScript = "#age > 18 && #vip.contains(\"vip\")";

  public OGNLRule() {
    rootContext = (OgnlContext) Ognl.createDefaultContext(this,
        memberAccess,
        new DefaultClassResolver(),
        new DefaultTypeConverter());

    try {
      executeExpression = Ognl.parseExpression(executeScript);
      evaluateExpression = Ognl.parseExpression(evaluateScript);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @SneakyThrows
  @Override
  public boolean execute(Map<String, Object> parameters) {
    return (boolean) Ognl.getValue(executeExpression, parameters, rootContext.getRoot());

  }

  @SneakyThrows
  @Override
  public boolean evaluate(Map<String, Object> parameters) {
    return (boolean) Ognl.getValue(evaluateExpression, parameters, rootContext.getRoot());
  }
}
